﻿using System;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace MyCode.Project.WebApi.App_Filter
{
    /// <summary>
    /// 把接口传参的字符串类型去掉空格trim()
    /// </summary>
    public class TrimStringsAttribute : ActionFilterAttribute
    {
        public static int i = 0; //限制嵌套循环的次数，防止死循环
        public override void OnActionExecuting(HttpActionContext filterContext)
        {         
            if (filterContext != null && filterContext.ActionArguments != null)
            {
                var parameters = filterContext.ActionArguments;
                foreach (var parameter in parameters)
                {
                    if (parameter.Value == null)
                    {
                        continue;
                    }
                    var properties = parameter.Value.GetType().GetProperties();
                    foreach (var property in properties)
                    {
                        if (property.PropertyType == typeof(string))
                        {
                            string value = (string)property.GetValue(parameter.Value);
                            if (value != null)
                            {
                                property.SetValue(parameter.Value, value.Trim());
                            }
                        }
                        else if (property.PropertyType.IsClass)
                        {
                            var subObj = property.GetValue(parameter.Value);
                            if (subObj != null)
                            {
                                RemoveWhiteSpace(subObj);
                            }
                        }
                    }
                }
            }
            i = 0;
        }

        public static void RemoveWhiteSpace<T>(T obj) where T : class
        {
            i++;
            if (i > 100)
            {
                return;
            }
            PropertyInfo[] properties = obj.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if (property.PropertyType == typeof(string))
                {
                    string value = (string)property.GetValue(obj);
                    if (value != null && !string.IsNullOrWhiteSpace(value))
                    {
                        property.SetValue(obj, value.Trim());
                    }
                }
                else if (property.PropertyType.IsClass)
                {
                    try
                    {
                        var subObj = property.GetValue(obj);
                        if (subObj != null)
                        {
                            RemoveWhiteSpace(subObj);
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
        }
    }
}